package com.cnpc.ds.client;

import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 消息中心 发送请求客户端
 *
 * @author  jyq
 */
@Service
@Slf4j
public class FileClient {
    @Value("${http.base-file-service}")
    private String address;
    /**
     * 上传文件 eg:请求成功，结果:{"code":"OK","message":"成功","data":{"file":"62f046d663674daf8c0b53a7e62f84b4"}}
     * @param uploadFile 上传pdf
     * @return file 文件主键id
     */
    public String uploadFile(MultipartFile uploadFile){
        try {
            InputStreamResource isr = new InputStreamResource(uploadFile.getInputStream(),
                    uploadFile.getName());
            Map<String, Object> params = new HashMap<>();
            params.put("file", isr);
            //http请求创建
            HttpRequest httpRequest = HttpUtil.createPost(address + "/upload").form(params);
            //http请求发送
            HttpResponse execute = httpRequest.execute();
            String body = execute.body();
            log.info("请求url-{},结果:{}",address + "/upload",body);
            if(execute.isOk()){
                JSONObject resultJson = JSONObject.parseObject(body);
                JSONObject data = resultJson.getJSONObject("data");
                if(ObjectUtil.isNotEmpty(data)){
                    return data.getString("file");
                }
            }
        }catch (Exception e){
            log.info("请求失败，原因:{}",e);
        }
        return null;
    }

    /**
     * 下载文件
     * @param fileId 文件id
     * @return file
     */
    public File download(String fileId,String fileName){
        try {
            Assert.notNull(fileId, "fileId参数不能为空");
            log.info("请求url：{}",address +"/download?fileId="+fileId);
            File file = new File(System.getProperty("user.dir")+"/download/"+fileName);
            long download = HttpUtil.downloadFile(address + "/download" + "?fileId=" + fileId, file);
            if(download>0){
                log.info("请求成功，创建文件:{}",file.getPath());
                return file;
            }
        }catch (Exception e){
            log.error("请求失败，文件id{},文件名{}，原因:{}",fileId,fileName,e);
            throw new IllegalArgumentException("文件下载失败");
        }
        return null;
    }

    /**
     * 删除文件  http://engineering.design.klmy.eisc.cnpc/api/base-file-service/delete?fileId=2c8085c78850a88f01900a7dc2750060
     * @param fileId 文件id
     * @return file
     */
    public void delete(String fileId){
        try {
            Assert.notNull(fileId, "fileId参数不能为空");
            HttpResponse execute = HttpUtil.createGet(address + "/delete?fileId=" + fileId).execute();
            log.info("请求url：{},结果{}",address +"/delete?fileId="+fileId,execute.body());
        }catch (Exception e){
            log.info("请求失败，请求url：{},结果{}",address +"/delete?fileId="+fileId,e.getMessage());
            throw new IllegalArgumentException("文件删除失败");
        }
    }

    /**
     * 下载文件
     * @param fileId 文件id
     * @return file
     */
    public String index(String fileId){
        try {
            Assert.notNull(fileId, "fileId参数不能为空");
            HttpRequest request = HttpUtil.createGet(address + "/index?fileId=" + fileId);
            HttpResponse response = request.execute();
            String body = response.body();
            log.info("请求url-{},结果:{}",address + "/index/fileId="+fileId,body);
            if(response.isOk()){
                JSONObject resultJson = JSONObject.parseObject(body);
                if("OK".equals(resultJson.getString("code"))){
                    JSONObject data = resultJson.getJSONObject("data");
                    return data.getString("fileName");
                }
            }
        }catch (Exception e){
            log.error("请求失败，接口/index，文件id{}原因:{}",fileId,e);
        }
        return null;
    }
}

